package com.newenergy.wisehome.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.config.Constants;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.ui.widget.wheelview.adapter.ArrayWheelAdapter;
import com.newenergy.wisehome.ui.widget.wheelview.adapter.NumericWheelAdapter;
import com.newenergy.wisehome.ui.widget.wheelview.listener.OnItemSelectedListener;
import com.newenergy.wisehome.ui.widget.wheelview.view.WheelView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.ISupportFragment;

/**
 * Created by kyx on 2018/5/28.
 *
 */

public class SetTimingFragment extends BaseFragment {


    private static String ARG_SETTIMING="arg_settiming";
    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.settime)
    TextView mSettime;
    @BindView(R.id.time)
    WheelView mTime;
    @BindView(R.id.hour)
    WheelView mHour;
    @BindView(R.id.minute)
    WheelView mMinute;
    @BindView(R.id.btn_open)
    Button mBtnOpen;
    @BindView(R.id.btn_close)
    Button mBtnClose;
    @BindView(R.id.tv_timeDesc)
    TextView mTvTimeDesc;

    List<String> times = new ArrayList<>();
    private int mTempTime;
    private int mTempHour;
    private int mTempMinute;

    protected BallLight mGroup;

    private IntentFilter intentFilter;

    private TimeChangeReceiver timeChangeReceiver;

    private String mNoon="";//默认为上午
    private String mLanguage;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_settiming;

    }

    public static ISupportFragment newInstance(BallLight group) {
        Bundle args = new Bundle();
        args.putParcelable(ARG_SETTIMING, group);
        SetTimingFragment fragment = new SetTimingFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void init(View rootView) {
        mGroup=getArguments().getParcelable(ARG_SETTIMING);
        mTvPage.setText(mGroup.getName());
        mLanguage = LocaleUtil.getLanguage();

        intData();
        initListener();

        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);//每分钟变化
//        intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);//设置了系统时区
//        intentFilter.addAction(Intent.ACTION_TIME_CHANGED);//设置了系统时间

        timeChangeReceiver = new TimeChangeReceiver();
        mainActivity.registerReceiver(timeChangeReceiver, intentFilter);

        long currentTimeMillis = System.currentTimeMillis()/1000/60;
        long endTime = 0L;
        String timeDesc = "";
        if (mGroup.getGroupId().equals("00")) {
            endTime = SPUtil.getLong(Constants.ENDTIME,0L);
            timeDesc = SPUtil.getString(Constants.TIMEDESC, "");
            /*List<BallLight> allBallLight = mBallLightDao.getAllBallLight();

            for (BallLight ballLight:allBallLight) {
                ballLight.setEndTime(endTime);
                ballLight.setTimeDesc(timeDesc);
                mBallLightDao.updateBallLight(ballLight);
            }*/

        }else {
            endTime = mGroup.getEndTime();
            timeDesc = mGroup.getTimeDesc();
        }


        if (currentTimeMillis>endTime){
            mTvTimeDesc.setText("");
        }else {
            mTvTimeDesc.setText(timeDesc);
        }


        Log.e("LFX", "currentTimeMillis==" + currentTimeMillis + "endTime==" + endTime);

    }

    public void intData() {
        times.clear();
        Calendar calendar = Calendar.getInstance();

        mHour.setAdapter(new NumericWheelAdapter(1, 12));
        int hours = calendar.get(Calendar.HOUR_OF_DAY);


        mMinute.setAdapter(new NumericWheelAdapter(0, 59));
        int minutes = calendar.get(Calendar.MINUTE);
        mTempMinute=minutes;
        mMinute.setCurrentItem(minutes);


        times.add(getString(R.string.tv_moring));
        times.add(getString(R.string.tv_noon));
        mTime.setAdapter(new ArrayWheelAdapter(times));
        mTime.setCyclic(false);
        mHour.setCyclic(false);
        mMinute.setCyclic(false);
        if (hours > 12) {
            mTime.setCurrentItem(1);
            mHour.setCurrentItem(hours-13);
            mTempHour=hours-12;
            mTempTime = 12;
        }else {
            mTime.setCurrentItem(0);
            mHour.setCurrentItem(hours-1);
            mTempHour=hours;
            mTempTime = 0;
        }
        getLefTotal();

    }

    public void initListener() {
        mTime.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                if (index == 0) {
                    mTempTime = 0;
                }else {
                    mTempTime = 12;
                }
                mNoon = times.get(index);
                getLefTotal();
            }

        });

        mHour.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                mTempHour = index + 1;
                getLefTotal();
            }
        });

        mMinute.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                mTempMinute = index;
                getLefTotal();
            }
        });
    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_open, R.id.btn_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
            case R.id.btn_open:
                int openTotal = getLefTotal();
                String data1 = numToHexs(openTotal)+"0000";
                AppManager.getInstance(mainActivity).commandCmd("07",mGroup.getFamilyId(),mGroup.getGroupId(),data1,"000100",mCurrFamily.getSeed(),mCurrFamily.getFeedback());
                UpdateTimeDesc(getString(R.string.tv_open),openTotal);
                break;
            case R.id.btn_close:
                int closeTotal = getLefTotal();
                String data = numToHexs(closeTotal)+"0000";
                AppManager.getInstance(mainActivity).commandCmd("07",mGroup.getFamilyId(),mGroup.getGroupId(),data,"000000",mCurrFamily.getSeed(),mCurrFamily.getFeedback());
                UpdateTimeDesc(getString(R.string.tv_close),closeTotal);
                break;
        }
    }


    private void UpdateTimeDesc(String state,int time) {
        BallLightDao ballLightDao = new BallLightDao(getContext());
        if (mTempTime == 0) {
            mNoon = times.get(0);
        }else {
            mNoon = times.get(1);
        }
        long currentTimeMillis = System.currentTimeMillis()/1000/60 ;
        long endTime = currentTimeMillis+ time;
        String minute = "";
        if (mTempMinute <= 9) {
            minute = "0" + mTempMinute;
        }else {
            minute = mTempMinute+"";
        }
        String timeDesc = "";
        if (mLanguage.equals("zh")) {
           timeDesc = mNoon + mTempHour + getString(R.string.tv_h) + minute + getString(R.string.tv_m) + state;
        }else {
            timeDesc = mNoon+ getString(R.string.tv_kongge) + mTempHour + getString(R.string.tv_h) + minute + getString(R.string.tv_kongge) + state;
        }


        mTvTimeDesc.setText(timeDesc);
        if (mGroup.getGroupId().equals("00")) {
            SPUtil.put(Constants.ENDTIME, endTime);
            SPUtil.put(Constants.TIMEDESC, timeDesc);
            List<BallLight> allBallLight = ballLightDao.getAllBallLight();

            for (BallLight ballLight:allBallLight) {
                ballLight.setEndTime(endTime);
                ballLight.setTimeDesc(timeDesc);
                ballLightDao.updateBallLight(ballLight);
            }
        } else {
            mGroup.setTimeDesc(timeDesc);
            mGroup.setEndTime(endTime);
            ballLightDao.updateBallLight(mGroup);
        }

        Log.e("LFX", "endTime===" + endTime);
    }

    private void checkValidityTime() {
        BallLightDao ballLightDao = new BallLightDao(getContext());
        long currentTimeMillis = System.currentTimeMillis()/1000/60;
        long endTime = 0L;
        if (mGroup.getGroupId().equals("00")) {
            endTime = SPUtil.getLong(Constants.ENDTIME, 0L);
        }else {
            endTime = mGroup.getEndTime();
        }

        Log.e("LFX", "currentTimeMillis==" + currentTimeMillis + "endTime==" + endTime);
        if (currentTimeMillis >=endTime) {
            mTvTimeDesc.setText("");
            if (mGroup.getGroupId().equals("00")) {
                SPUtil.put(Constants.ENDTIME, 0L);
                SPUtil.put(Constants.TIMEDESC, "");
                List<BallLight> allBallLight = ballLightDao.getAllBallLight();

                for (BallLight ballLight:allBallLight) {
                    ballLight.setEndTime(0);
                    ballLight.setTimeDesc("");
                    ballLightDao.updateBallLight(ballLight);
                }
            } else {
                mGroup.setTimeDesc("");
                mGroup.setEndTime(0);
                ballLightDao.updateBallLight(mGroup);
            }

        }
    }


    public int getLefTotal() {
    int noon = mTempTime ==12 ? 1 :0;
     int h1=mTempHour;
     int m1 =mTempMinute;
     h1 =(noon==0)? h1:  h1 + 12;

     int nowHour =Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
     int nowMinute =Calendar.getInstance().get(Calendar.MINUTE);

        int leftTotal =0;
        //现在总时间
        int nowTotal = nowHour * 60 + nowMinute;
        //预定总时间
        int expectedTotal =  h1 * 60 + m1;
        if (expectedTotal >= nowTotal) {
            leftTotal = expectedTotal - nowTotal;
        }else{
            leftTotal = 24*60 + expectedTotal - nowTotal;
        }
      int hour = leftTotal / 60;
      int minute=leftTotal % 60;

    if (leftTotal > 720) {
        mBtnOpen.setEnabled(false);
        mBtnClose.setEnabled(false);
        mSettime.setText(getString(R.string.set_time_no_more_than));
        mSettime.setTextColor(Color.RED);
    } else if (leftTotal == 0) {
        mBtnOpen.setEnabled(false);
        mBtnClose.setEnabled(false);
        mSettime.setText(getString(R.string.set_time_more_than));
        mSettime.setTextColor(Color.RED);
    }else{
        mBtnOpen.setEnabled(true);
        mBtnClose.setEnabled(true);
        if (mLanguage.equals("zh")) {
            mSettime.setText(hour + getString(R.string.tv_hour) + minute + getString(R.string.tv_minute));
        }else {
            mSettime.setText(getString(R.string.tv_action)+hour + getString(R.string.tv_hour) + minute+ getString(R.string.tv_minutes) );
        }
        mSettime.setTextColor(getResources().getColor(R.color.text_device_n));
    }

//        Log.i("LFX", "getLefTotal:  leftTotal= "+leftTotal + "   hour="+hour+"   minute="+minute);
        return leftTotal;
    }



    class TimeChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Intent.ACTION_TIME_TICK:
                    //每过一分钟 触发
                    getLefTotal();
                    checkValidityTime();
//                    Toast.makeText(context, "1 min passed", Toast.LENGTH_SHORT).show();
                    break;
                /*case Intent.ACTION_TIME_CHANGED:
                    //设置了系统时间
                    Toast.makeText(context, "system time changed", Toast.LENGTH_SHORT).show();
                    break;
                case Intent.ACTION_TIMEZONE_CHANGED:
                    //设置了系统时区的action
                    Toast.makeText(context, "system time zone changed", Toast.LENGTH_SHORT).show();
                    break;*/
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mainActivity.unregisterReceiver(timeChangeReceiver);
    }
}
